// pages/buy/index.js
import Config from '../../etc/config'

const {
  $Toast
} = require('../../components/dist/base/index');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    attitudeRate: 0,
    speedRate: 0,
    content: '',
    tempFilePaths: [],
    uploadImgs: [],
    orderId: '',
    disabled: false
  },
  // 态度
  handlerAttitudeRate(e) {
    const index = e.detail.index;
    this.setData({
      'attitudeRate': index
    })
  },
  //速度
  handlerSpeedRate(e) {
    const index = e.detail.index;
    this.setData({
      'speedRate': index
    })
  },
  uploadImg(e) {
    this.setData({
      uploadImgs: []
    })
    var that = this;
    wx.chooseImage({
      success: function(res) {
        var file = that.data.tempFilePaths;
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          file.push(res.tempFilePaths[i]);
        }
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          tempFilePaths: file
        })
        // var files = that.data.tempFilePaths;
        //
        // var host = Config.basePath + '/file/upload';
        // console.log('host:::', host)
        // that.uploadimgs({
        //   url: host,//这里是你图片上传的接口
        //   path: files//这里是选取的图片的地址数组
        // });
      }
    })
  },
  //多张图片上传
  uploadimgs: function(data) {
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    let token = wx.getStorageSync('token')
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'file',
      header: {
        'access_token': token
      },
      success: (resp) => {
        success++;
        that.setData({
          dataId: resp.data
        })
        if (resp.statusCode == 200) {
          let res = JSON.parse(resp.data)
          if (res.code == 0) {
            let name = res.data.bucketName + '-' + res.data.fileName
            this.data.uploadImgs.push(name)
            this.setData({
              uploadImgs: this.data.uploadImgs
            })
          }
        }
        //这里可能有BUG，失败也会执行这里
      },
      fail: (res) => {
        fail++;
      },
      complete: () => {
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用
          // this.save();//上传完后再执行的方法
          // 评价
          let images = ''
          for (let i = 0; i < this.data.uploadImgs.length; i++) {
            images += this.data.uploadImgs[i] + ','
          }
          let params = {
            orderId: this.data.orderId,
            attitudeScore: this.data.attitudeRate,
            speedScore: this.data.speedRate,
            content: this.data.content,
            images: images
          }
          let token = wx.getStorageSync('token')
          Config._post('/order/comment', token, params).then(res => {
            if (res.code == 0) {
              // 用户基本信息展示
              $Toast({
                content: '评论成功'
              });
              var pages = getCurrentPages(); // 获取页面栈
              var prevPage = pages[pages.length - 2]; // 上一个页面
              prevPage.setData({
                current: '2'
              })
              wx.navigateBack()
            } else {
              $Toast({
                content: '评论失败'
              });
            }
          })

        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimgs(data);
        }

      }
    });
  },
  valueInput(e) {
    this.setData({
      content: e.detail.value
    })
  },
  handlerPublishComment() {
    if (this.data.tempFilePaths.length > 0) {
      var files = this.data.tempFilePaths;

      var host = Config.basePath + '/file/upload';
      this.uploadimgs({
        url: host, //这里是你图片上传的接口
        path: files //这里是选取的图片的地址数组
      });
    } else {
      let params = {
        orderId: this.data.orderId,
        attitudeScore: this.data.attitudeRate,
        speedScore: this.data.speedRate,
        content: this.data.content
      }
      let token = wx.getStorageSync('token')
      Config._post('/order/comment', token, params).then(res => {
        if (res.code == 0) {
          // 用户基本信息展示
          $Toast({
            content: '评论成功'
          });
          wx.switchTab({
            url: '../order/index?key=2',
          })
        } else {
          $Toast({
            content: res.msg
          });
        }
      })

    }
  },

  deleteImg(e) {
    this.data.tempFilePaths.splice(e.currentTarget.dataset.index,1)
    this.setData({
      tempFilePaths:this.data.tempFilePaths
    })
  },

  onLoad: function(options) {
    wx.hideShareMenu()
    this.setData({
      orderId: options.orderId
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})